package com.example.day12_7_12_1.util;


import com.example.day12_7_12_1.WanService;
import com.example.day12_7_12_1.base.Constants;

import java.io.File;
import java.io.IOException;

import okhttp3.Cache;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class HttpUtil {
    private static volatile HttpUtil sHttpUtil = null;
    private Retrofit.Builder mBuilder;

    private HttpUtil() {
        OkHttpClient okHttpClient = initOkHttp();
        initRetrofit(okHttpClient);
    }

    private void initRetrofit(OkHttpClient okHttpClient) {
        mBuilder = new Retrofit.Builder()
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create());
    }

    private OkHttpClient initOkHttp() {
        File cacheFile = new File(Constants.PATH_CACHE);
        Cache cache = new Cache(cacheFile, 1024 * 1024 * 50);
        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(new LogInterceptor())
                .cache(cache)
                .retryOnConnectionFailure(true)
                .build();

        return client;

    }

    public static HttpUtil getInstance() {
        if (sHttpUtil == null) {
            synchronized (HttpUtil.class) {
                if (sHttpUtil == null) {
                    sHttpUtil = new HttpUtil();
                }
            }
        }

        return sHttpUtil;
    }

    class LogInterceptor implements Interceptor {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Response reponse = chain.proceed(request);
            LogUtil.print(reponse.peekBody(2048).string());
            return reponse;
        }
    }



    volatile WanService mWanService = null;

    public WanService getWanService() {
        if (mWanService == null) {
            synchronized (HttpUtil.class) {
                if (mWanService == null) {
                    mWanService = mBuilder.baseUrl(WanService.sWanUrl)
                            .build()
                            .create(WanService.class);
                }
            }
        }

        return mWanService;
    }
}
